/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.anniversary.domain.Student;
import me.zhengjie.modules.anniversary.repository.StudentRepository;
import me.zhengjie.modules.anniversary.service.StudentService;
import me.zhengjie.modules.anniversary.service.dto.StudentDto;
import me.zhengjie.modules.anniversary.service.dto.StudentQueryCriteria;
import me.zhengjie.modules.anniversary.service.mapstruct.StudentMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Jiayin Wei
* @date 2020-07-27
**/
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {

    private final StudentRepository studentRepository;
    private final StudentMapper studentMapper;

    @Override
    public Map<String,Object> queryAll(StudentQueryCriteria criteria, Pageable pageable){
        Page<Student> page = studentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(studentMapper::toDto));
    }

    @Override
    public List<StudentDto> queryAll(StudentQueryCriteria criteria){
        return studentMapper.toDto(studentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StudentDto findById(Long id) {
        Student student = studentRepository.findById(id).orElseGet(Student::new);
        ValidationUtil.isNull(student.getId(),"Student","id",id);
        return studentMapper.toDto(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StudentDto create(Student resources) {
        return studentMapper.toDto(studentRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Student resources) {
        Student student = studentRepository.findById(resources.getId()).orElseGet(Student::new);
        ValidationUtil.isNull( student.getId(),"Student","id",resources.getId());
        student.copy(resources);
        studentRepository.save(student);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            studentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StudentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StudentDto student : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户ID", student.getUserId());
            map.put("名称", student.getName());
            map.put("性别（0：男，1：女）", student.getGender());
            map.put("出生年月", student.getBirthDate());
            map.put("民族ID", student.getNationId());
            map.put("政治面貌ID", student.getPoliticalId());
            map.put("入学年份", student.getEnterDate());
            map.put("学历层次ID", student.getEducationalLevelId());
            map.put("学院ID", student.getAcademyDepartId());
            map.put("系部ID", student.getFacultyDepartId());
            map.put("专业ID", student.getMajorDepartId());
            map.put("班级ID", student.getClassDepartId());
            map.put("身份证号码", student.getIdCardNo());
            map.put("生源地", student.getBirthPlace());
            map.put("目前所从事行业", student.getIndustry());
            map.put("工作单位", student.getWorkUnit());
            map.put("职称", student.getPostitional());
            map.put("职务", student.getJob());
            map.put("目前所在地", student.getAddress());
            map.put("联系电话", student.getPhone());
            map.put("QQ号", student.getQq());
            map.put("微信号", student.getWeixin());
            map.put("简介", student.getBrief());
            map.put("认证状态（0：未认证，1：已认证）", student.getVerifyStatus());
            map.put("创建者名称", student.getCreateBy());
            map.put("创建时间", student.getCreateTime());
            map.put("修改者名称", student.getUpdatedBy());
            map.put("修改时间", student.getUpdateTime());
            map.put("排序", student.getSort());
            map.put("备注", student.getRemark());
            map.put("是否启用", student.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}